package com.edu.chat.web.config;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.edu.buservice.util.model.TenantUtil;
import com.edu.chat.web.common.enums.ResultCodeEnum;
import com.edu.chat.web.common.model.BizException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @program: KQAIA
 * @description:
 * @author: 无恙
 * @create: 2025-03-21 10:56
 **/
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

	@Override
	public void insertFill(MetaObject metaObject) {
		log.info("开始插入填充...");
		verify();
		this.strictInsertFill(metaObject, "createdBy", String.class, TenantUtil.getUserId());
		this.strictInsertFill(metaObject, "createdAt", Date.class, new Date());
		this.strictInsertFill(metaObject, "updatedBy", String.class, TenantUtil.getUserId());
		this.strictInsertFill(metaObject, "updatedAt", Date.class, new Date());
		this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
		this.strictInsertFill(metaObject, "tenantId", String.class, TenantUtil.getTenantId());
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		log.info("开始更新填充...");
		verify();
		this.strictInsertFill(metaObject, "updatedBy", String.class, TenantUtil.getUserId());
		this.strictInsertFill(metaObject, "updatedAt", Date.class, new Date());
	}

	private static void verify() {
		String tenantId = TenantUtil.getTenantId();
		String loginIdAsString = TenantUtil.getUserId();

		if(StringUtils.isBlank(tenantId) || StringUtils.isBlank(loginIdAsString)){
			throw new BizException(ResultCodeEnum.DATA_EXCEPTION, "租户ID和登录用户不能为空");
		}
	}
}